package com.hrzyit.whistle.cases.ui.fragment

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hrzyit.base.common.BaseConstant
import com.hrzyit.base.ext.onClick
import com.hrzyit.base.ui.fragment.BaseMvpFragment
import com.hrzyit.base.utils.AppPrefsUtils
import com.hrzyit.whistle.cases.R
import com.hrzyit.whistle.cases.data.bean.SelectUserDeptInfoVo
import com.hrzyit.whistle.cases.data.bean.UserDeptInfoVo
import com.hrzyit.whistle.cases.event.SelectDeptAndUserEvent
import com.hrzyit.whistle.cases.injection.component.DaggerCaseCenterComponent
import com.hrzyit.whistle.cases.injection.module.CaseCenterModule
import com.hrzyit.whistle.cases.presenter.SelectDeptUserForApprovePresenter
import com.hrzyit.whistle.cases.presenter.view.SelectDeptUserForApproveView
import com.hrzyit.whistle.cases.ui.adapter.SelectDeptUserInfoAdapter
import kotlinx.android.synthetic.main.fragment_select_dept_user_approve.*
import me.yokeyword.indexablerv.IndexableLayout
import org.greenrobot.eventbus.EventBus

/**
 * 选择单位和人员:批示环节 Fragment
 * @author YangWei
 * @date 2019/4/29
 */
class SelectDeptAndUserForApproveFragment : BaseMvpFragment<SelectDeptUserForApprovePresenter>(),
    SelectDeptUserForApproveView {

    companion object {
        const val TAG = "选择单位和人员:批示环节 Fragment"
    }

    private lateinit var activity: Activity
    private lateinit var mAdapter: SelectDeptUserInfoAdapter
    private var userId: Long = 0L
    private var caseId: Long = 0L

    /**
     * 获取 Activity 容器引用
     */
    override fun onAttach(context: Context?) {
        super.onAttach(context)
        activity = context as Activity
    }

    /**
     * 关联 Fragment 视图
     */
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        // 加载 Fragment
        return inflater.inflate(R.layout.fragment_select_dept_user_approve, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initView()

        initData()
    }

    /**
     * 初始化视图
     */
    private fun initView() {
        // 初始化联系人索引选择器
        val indexLayout = mSelectDeptAndUserApproveIndexLayout as IndexableLayout
        indexLayout.setLayoutManager(LinearLayoutManager(activity))

        // setAdapter
        mAdapter = SelectDeptUserInfoAdapter(activity)
        indexLayout.setAdapter(mAdapter)

        // set Material Design OverlayView
        indexLayout.setOverlayStyle_MaterialDesign(Color.BLUE)

        // 全字母排序。  排序规则设置为：每个字母都会进行比较排序；速度较慢
        indexLayout.setCompareMode(IndexableLayout.MODE_FAST)

        // set Listener
        // View v, int originalPosition, int currentPosition, T entity)
        mAdapter.setOnItemContentClickListener { v, oPos, cPos, entity ->

            // 取消其它人员列表选中状态
            entity.isChecked = !entity.isChecked
            mAdapter.notifyDataSetChanged()

        }
        // 注册增加批示接收人按钮事件

        mSelectDeptAndUserApproveHeaderBar.getRightView().onClick {
            val userIdList = mutableListOf<Long>()
            val userNameList = mutableListOf<String>()
            val deptIdList = mutableListOf<Long>()
            val deptNameList = mutableListOf<String>()
            val userDeptInfoVoList = mutableListOf<UserDeptInfoVo>()
            // return be checked item
            mAdapter.items.filter {
                it.isChecked
            }.forEach { item ->
                item.toUserList.forEach {
                    userIdList.add(it.userId)
                    deptIdList.add(it.deptId)
                    userNameList.add(it.userName)
                    deptNameList.add(it.deptName)
                    userDeptInfoVoList.add(it)
                }
            }
            val selectDeptAndUserEvent = SelectDeptAndUserEvent(
                deptIdList, deptNameList.joinToString("、"),
                userIdList, userNameList.joinToString("、"),
                userDeptInfoVoList
            )
            EventBus.getDefault().post(selectDeptAndUserEvent)
            // 返回批示页面
            activity.finish()
        }
    }

    /**
     * 初始化数据
     */
    private fun initData() {
        // 获取案件id
        this.caseId = activity.intent.getLongExtra("caseId", 0L)

        // 当前操作人id
        this.userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)

        // 获取当前操作人可选单位信息
        mPresenter.selectDeptUserForApproveList(caseId, userId)
    }

    /**
     * Dagger2 注入 Service
     */
    override fun injectComponent() {

        DaggerCaseCenterComponent.builder()
            .activityComponent(mActivityComponent)
            .caseCenterModule(CaseCenterModule())
            .build()
            .inject(this)
        mPresenter.mView = this
    }

    /**
     *  获取当前操作人可选单位回调方法
     */
    override fun onGetSelectDeptUserForApproveListSuccess(result: MutableList<SelectUserDeptInfoVo>) {
        result.let {
            mAdapter.setDatas(result)
        }
    }

    override fun onSaveApproveSuccess(result: Boolean) {
        Log.e(TAG, "onSaveApproveSuccess：$result")
    }
}